import query from '@dfeidao/atom-nodejs/db/query';
// import { systemid } from './config';

interface Message {
	productid: string;
	group_id: string;
	role_allot_id: string;
	num: number;
}
interface Data {
	field: string;
	operate: string;
	field_value: string;
	connector: string;
	group_id: string;
}
export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const systemid = '12';

	const { exec, prepare } = query(action_id, session_id, systemid);
	const productid = msg.productid;
	const role_allot_id = msg.role_allot_id;
	const group_id = msg.group_id;
	const num = msg.num;
	let str = "";
	// let data: Object[];
	if (num === 1) {
		prepare('allot_conditions', ['connector', 'group_id', 'field', 'operate', 'field_value', 'priority'], { productid, group_id }, 199, 1, ['priority'], []);
		const [data] = await exec<Data>();
		data.map((v, i) => {
			if (i === 0) {
				str += v.field + " " + v.operate + " " + v.field_value + " ";
			} else if (i === data.length - 1) {
				str += v.connector + " " + v.field + " " + v.operate + " " + v.field_value;
			} else {
				str += v.connector + " " + v.field + " " + v.operate + " " + v.field_value + " ";
			}
		});
	}

	if (num === 2) {
		prepare('allot_conditions_group', ['group_id', 'priority', 'connector'], { productid, role_allot_id, parent_group_id: group_id }, 199, 1, [], []);
		const [data1] = await exec<Data>();
		const arr = data1.map((v) => {
			return v.group_id;
		});
		prepare('allot_conditions', ['connector', 'group_id', 'field', 'operate', 'field_value', 'priority'], { productid, group_id: { $in: arr } }, 199, 1, ['priority'], []);
		const [data] = await exec<Data>();
		const aa = arr.map((item) => {
			const cdata = data.filter((a) => {
				return a.group_id === item;
			});
			// console.log(cdata)
			let str1 = "";
			cdata.map((v, i) => {
				if (i === 0) {
					if (cdata.length !== 1) {
						str1 += v.field + " " + v.operate + " " + v.field_value + " ";
					} else {
						str1 += v.field + " " + v.operate + " " + v.field_value;
					}
				} else if (i === cdata.length - 1) {
					str1 += v.connector + " " + v.field + " " + v.operate + " " + v.field_value;
				} else {
					str1 += v.connector + " " + v.field + " " + v.operate + " " + v.field_value + " ";
				}
			});
			// console.log(str1)
			return str1;
		});
		// console.log(data1[0])
		aa.map((v, i) => {
			if (i === aa.length - 1) {
				str += "(" + v + ")";
			} else {
				str += "(" + v + ") " + data1[0].connector + " ";
			}
		});
	}

	str = "(" + str + ")";

	return str;
}
